#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymongo import Connection
from cupblog.config.server import *
from cupblog.func import get_current_blog

__author__ = 'lihaoquan'

#创建博客数据库的索引
def ensure_index_of_blog(db):
    db.articles.ensure_index([('Id', -1)])
    db.articles.ensure_index([('PostOn', -1)])
    db.articles.ensure_index([('IsPublic', -1)])
    db.articles.ensure_index('Tags')
    db.articles.ensure_index('Categories')
    db.categories.ensure_index([('Title', 1)])



#建立数据库链接
def connect_database(request):
    blog = get_current_blog(request)
    if blog is None:
        return None

    name = blog[STR_NAME]
    host = None
    if DATABASE_USERNAME is None:
        host = 'mongodb://%s:%d' % (DATABASE_HOST, DATABASE_PORT)
    else:
        host = 'mongodb://%s:%s@%s:%d' % (DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT)

    c = Connection(host)

    return c[DEFAULT_DB_FLAG+'_blogs_'+name]


#连接到账户数据库
def connect_account_database(request):
    if DATABASE_USERNAME is None:
        host = 'mongodb://%s:%d' % (DATABASE_HOST, DATABASE_PORT)
    else:
        host = 'mongodb://%s:%s@%s:%d' % (DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT)

    print '--->'+host

    c = Connection(host)
    return c[DEFAULT_DB_FLAG+'_users']

